<template>
	<view class="number-box l-f">
		<view @click="onSub" 
		class="number-boxr_btn"
		:class="modelValue <= min ? 'number-box_btn-disabled' : ''"
		hover-class="hover-class">
			<uni-icons type="minus-filled" size="66rpx" color="#333333"></uni-icons>
		</view>
		<input
		class="number-box_input" 
		type="number"
		:value="modelValue"
		@input="onInput"
		 @blur="onBlur"/>
		<view @click="onAdd" 
		class="number-box_btn"
		:class="modelValue >= max ? 'number-box_btn-disabled' : ''"
		hover-class="hover-class">
			<uni-icons type="plus-filled" size="66rpx" color="#DE483D"></uni-icons>
		</view>
	</view>
</template>

<script lang="ts" setup>
	import { ref, watch } from 'vue'
	const props = defineProps({
		min: {
			type: Number,
			default: 0
		},
		max: {
			type: Number,
			default: 999999999
		},
		modelValue: {
			type: Number,
			defautl: 0
		}
	})
	watch(() => props.max, () => {
	  emits('update:modelValue', 1)
	});
	const cacheValue = ref(props.modelValue)
	const onInput = ($event: any)=> {
		let value = $event.detail.value
		if(value) {
			value = parseInt(value)
		}else {
			value = 0
		}
		const reg = /^(0|[1-9][0-9]*)$/
		if(!reg.test(value)) {
			emits('update:modelValue', 0)
			setTimeout(()=> {
				emits('update:modelValue', cacheValue.value)
			},30)
		}else {
			// 防止手输超出最大值
			if(props.modelValue >= props.max) {
				cacheValue.value = props.max
				emits('update:modelValue', 0)
				setTimeout(()=> {
					emits('update:modelValue', props.max)
				},30)
				return 
			}else {
				cacheValue.value = value
				emits('update:modelValue', value)
			}
		}
		
	}
	const onBlur = () => {
		emits('update:modelValue', cacheValue.value)
	}
	const emits = defineEmits(['sub','add','update:modelValue'])
	const onSub = () => {
		if(props.modelValue <= props.min) return
		emits('sub')
	}
	const onAdd = () => {
		if(props.modelValue >= props.max) return
		emits('add')
	}
</script>

<style lang="scss" scoped>
.number-box {
	&_btn {
		&_icon {
			width: 80rpx;
			height: 80rpx;
		}
	}
	&_btn-disabled {
		opacity: .5;
	}
	&_input {
		width: 120rpx;
		height: 66rpx;
		line-height: 66rpx;
		font-size: 28rpx;
		color: #000000;
		font-weight: 700;
		margin: 0 10rpx;
		background-color: #FAFAFA;
		text-align: center;
		border-radius: 6rpx;
		padding: 0 15rpx;
		box-sizing: border-box;
	}
}
</style>